package conf

import (
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
)

var (
	configOnce sync.Once
	config     *Config
)

type Config struct {
	LogLevel string
	Host     string
	Port     int
	Mysql    Mysql
}

func Initialize(cfgFile string) {
	var err error
	var file string
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	} else {
		file, err = exec.LookPath(os.Args[0])
		if err != nil {
			logrus.Fatal(err)
		}
		file, err = filepath.Abs(file)
		if err != nil {
			logrus.Fatal(err)
		}
		execDir := file[0:strings.LastIndex(file, "/")]

		viper.SetConfigName("litter")
		viper.SetConfigType("yaml")
		viper.AddConfigPath("/etc/litter")
		viper.AddConfigPath("$HOME/.litter")
		viper.AddConfigPath(execDir)
	}
}

func GetConfig() (*Config, error) {
	var err error
	configOnce.Do(func() {
		config, err = prepareConfig()
	})
	return config, err
}

func prepareConfig() (*Config, error) {
	var (
		err error
	)

	err = viper.ReadInConfig()
	if err != nil {
		return nil, err
	}

	config = &Config{
		LogLevel: "debug",
		Host:     "127.0.0.1",
		Port:     8080,
		Mysql:    Mysql{},
	}

	//fmt.Println(config)
	err = viper.Unmarshal(config)
	if err != nil {
		return nil, err
	}
	return config, nil
}
